<template>
    <div>
        <el-checkbox-group v-model="modelValue.variableValue" :size="propJson.size" :disabled="propJson.isDisable" :info="selectOption" @change="checkBoxChange()">
            <el-checkbox v-for="item in options" :key="item.value"
                         :label="item.label" :value="item.value" />
        </el-checkbox-group>
    </div>
</template>

<script setup lang="ts" name="CheckBoxComponent">
import {computed, defineProps, ref} from "vue";
import {commonParamChange, getCommonParamObj} from "@/utils/commonParamUtil.ts";
import {useRouter} from "vue-router";
import jsonpath from "jsonpath";
import {doThirdServiceAction, doThirdServiceValue} from "@/utils/lowcode/thirdService.ts";

let props = defineProps(['propJson', 'commonParam']);

let propJson = computed(() => {return props['propJson']})
let commonParam = computed(() => {return props['commonParam']})

let router = useRouter();

let modelValue = computed(() => {
    let bindVariable= propJson.value.bindVariable;
    // 获取全局变量中的值
    let commonObj = getCommonParamObj(commonParam.value, bindVariable);
    if (!Array.isArray(commonObj.variableValue) && commonObj.variableValue) {
        let jsonArray = JSON.parse(commonObj.variableValue);
        commonParamChange(commonParam.value, commonObj.variableName, jsonArray);
    }
    return getCommonParamObj(commonParam.value, bindVariable)
})

let selectOption = computed(async () => {
    await doThirdServiceValue(propJson.value.actionInfo, commonParam.value, execThen, () => {}, null)
})

let options = ref([])

function execThen(resValue) {
    // 根据返回的结果解析label和value
    let optionsList = []
    for (let i = 0; i < resValue.length; i++) {
        let op = {label: "", value: ""}
        let info = resValue[i]
        let opLabel = jsonpath.query(info, propJson.value.optionLabel)
        let opValue = jsonpath.query(info, propJson.value.optionValue)
        if (opLabel.length > 0 && opValue.length > 0) {
            op.label = opLabel[0]
            op.value = opValue[0]
            optionsList.push(op)
        }
    }
    options.value = optionsList
}

function execChangeThen(awaitObj) {
    // 判断是否需要在下拉改变后重新加载页面
    if (propJson.value.isReloadPage && awaitObj.res) {
        router.go(0)
    }
}

async function checkBoxChange() {
    if (!propJson.value.isAddChangeAction) {
        return;
    }
    // 定义一个标志位，后续同步执行
    let awaitObj = {flag: false, res: true}
    await doThirdServiceAction(propJson.value.changeAction, awaitObj, commonParam.value, execChangeThen, ()=>{}, awaitObj);
}
</script>

<style scoped lang="less">

</style>